/*
 * BrianClarkeCPE301Design2.c
 *
 * Created: 3/13/2014 8:12:39 PM
 *  Author: Iguana
 */ 

#define F_CPU 8000000UL  					// Set clock to 8MHz
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>

char Twos = 0;
char Tens = 0;

int ModCHK(char count, int i)
{
	count++;								// Increase the number of falling edges [MOD2] or [MOD10]
	if (count == i)							// Check if count was reached
	{
		count == 0;							// Reset count
		if (i == 2)							// Check which mod was used [MOD2] or [MOD10]
		PORTD ^= (1<<7);					// Set 10th bit on the LED bar
		else
		PORTD ^= (1<<6);					// Set 9th bit on the LED bar
	}
	return count;							// Return the count since there is no pass by reference in C
}

ISR(INT0_vect)								//ISR for the INT0 vector.
{
	cli(); 									// Disable interrupts
	Twos = ModCHK(Twos, 2);
	sei(); 									// Re-enable interrupts
}

void DirectINIT()							// Initialize the direction of used Ports [PORTB] and [PORTD]
{
	DDRB   = 0xFF;							// Set the direction for LED bits 0-7 [PORTB]
	DDRD   = 0xc0;							// Set the direction for LED bits 6 and 7 [PORTD] pin 6 is every 10 cycles, bit 7 is every second falling edge
	PORTB = 0x00;							// Empty PORTB
	PORTD = 0x00;							// Empty PORTD
}

void TimerINIT()							// Initialize the timer bits [Timer0]
{
	TCCR0A = 0x00;							// Clear all bits
	TCCR0B = 0x03;							// Set the CS prescalar to 64
}

int main(void)
{
	unsigned char counter = 0; 				// Counter variable for displaying on PORTB
	DirectINIT();							// Initialize directions
	OCR0A = 127;							// 50% Duty Cycle
	TimerINIT();							// Initialize the timer
	
	EICRA = 0x02; 							// Set INT0 to trigger falling edge interrupts
	EIMSK = 0x01; 							// Enable INT0 interrupts.
	sei(); 									// Global interrupt enable
	
	while(1) 								// Endless loop
	{
		_delay_ms(500); 					// High for 500ms for the 0.5s delay
		counter++; 							// Increase the count on the falling edge
		PORTB = counter;					// Send [PORTB0-7] to bits 0-7 on the LED bar
		Tens = ModCHK(Tens, 10);
		_delay_ms(500); 					// Low for 500ms
	}
}


